package cn.sc.summer.constant.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import lombok.val;
import org.dozer.DozerBeanMapper;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * dozer 类型转化工具
 *
 * @author a-xin
 */
public class ConvertUtil {

    /**
     * 持有Dozer单例, 避免重复创建DozerMapper消耗资源.
     */
    private static final DozerBeanMapper dozerBeanMapper;

    static {
        dozerBeanMapper = new DozerBeanMapper();
    }

    /**
     * 对象通用转换
     *
     * @param source           源对象
     * @param destinationClass 目标类
     * @param <T>              目标对象泛型
     * @return 返回得到destinationClass
     */
    public static <T> T converter(Object source, Class<T> destinationClass) {
        return AssertUtil.functionIfPre(source, ObjectUtil::isNotNull, () -> {
            return dozerBeanMapper.map(source, destinationClass);
        }, null);
    }

    /**
     * 对象通用转换
     *
     * @param source 源对象
     * @return 返回得到destinationClass
     */
    public static Map<?, ?> convertToObjMap(Object source) {
        return AssertUtil.functionIfPre(source, ObjectUtil::isNotNull,
                () -> dozerBeanMapper.map(source, Map.class),
                new HashMap<>());
    }

    /**
     * 对象通用转换
     *
     * @param source 源对象
     * @return 返回得到destinationClass
     */
    public static Map<String, Object> convertToMap(Object source, String... properties) {
        return AssertUtil.functionIfPre(source, ObjectUtil::isNotNull, () -> {
            Map<?, ?> map = dozerBeanMapper.map(source, Map.class);
            Map<String, Object> resultMap = new HashMap<>();
            if (properties != null && properties.length > 0) {
                for (String property : properties) {
                    resultMap.put(property, map.getOrDefault(property, null));
                }
            } else {
                map.forEach((key, value) -> {
                    resultMap.put(key.toString(), value);
                });
            }
            return resultMap;
        }, new HashMap<>());
    }

    /**
     * 对象通用转换（反射）
     *
     * @param source 源对象
     * @return 返回得到destinationClass
     */
    public static Map<String, Object> convertMap(Object source) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            Field[] declaredFields = source.getClass().getDeclaredFields();
            for (Field field : declaredFields) {
                field.setAccessible(true);
                resultMap.put(field.getName(), field.get(source));
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return resultMap;
    }

    /**
     * 基于Dozer将对象A的值拷贝到对象B中.
     *
     * @param source            源数据
     * @param destinationObject 拷贝数据对象
     */
    public static void copyProperty(Object source, Object destinationObject) {
        dozerBeanMapper.map(source, destinationObject);
    }

    /**
     * 集合转换
     *
     * @param sourceList       源集合
     * @param destinationClass 目标类
     * @param <T>              泛型
     * @return 返回得到destinationClass的集合结果
     */
    public static <T> List<T> convertToList(List<?> sourceList, Class<T> destinationClass) {
        return AssertUtil.functionIfPre(sourceList, CollUtil::isNotEmpty, () -> sourceList.stream().map(source -> ConvertUtil.converter(source, destinationClass))
                .collect(Collectors.toList()), new ArrayList<>());
    }

    /**
     * json字符串转对象，带泛型,
     * 对象转换json字符串推荐使用：{@link ConvertUtil#toJsonString(Object)}
     *
     * @param data    json字符串
     * @param clsType 转换类型
     * @param <T>     转换泛型
     * @return 转换后数据
     */
    public static <T> T toObject(String data, TypeReference<T> clsType) {
        try {
            if (CharSequenceUtil.isBlank(data)) {
                return null;
            }
            val mapper = new ObjectMapper();
            mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
            return mapper.readValue(data, clsType);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 对象转json字符串,
     * json字符串转换对象(带泛型)推荐使用：{@link ConvertUtil#toObject(String, TypeReference)}
     *
     * @param data 对象
     * @return json字符串
     */
    public static <T> String toJsonString(T data) {
        try {
            val mapper = new ObjectMapper();
            mapper.configure(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS, false);
            return mapper.writeValueAsString(data);
        } catch (JsonProcessingException e) {
            return data.toString();
        }
    }

    /**
     * xml格式字符串转json字符串
     *
     * @param xml xml字符串
     * @return json字符串
     */
    public static String xmlToJsonStr(String xml) {
        try {
            XmlMapper xmlMapper = new XmlMapper();
            JsonNode jsonNode = xmlMapper.readTree(xml);
            ObjectMapper jsonMapper = new ObjectMapper();
            return jsonMapper.writeValueAsString(jsonNode);
        } catch (Exception e) {
            return xml;
        }
    }

}
